<?php

namespace plugin\sqmadmin\basic;

use think\Model;
use think\model\concern\SoftDelete;
use plugin\sqmadmin\utils\Snowflake;

/**
 * 模型基类
 * @package plugin\sqmadmin\basic
 */
class BaseModel extends Model
{
    use SoftDelete;
    // 删除时间
    protected $deleteTime = 'delete_time';
    // 添加时间
    protected $createTime = 'create_time';
    // 更新时间
    protected $updateTime = 'update_time';
    // 隐藏字段
    protected $hidden = ['delete_time'];
    // 只读字段
    protected $readonly = ['created_by', 'create_time'];
    
    // 定义ID字段类型
    protected $type = [
        'id' => 'integer',
    ];

    /**
     * 时间范围搜索
     */
    public function searchCreateTimeAttr($query, $value)
    {
        $query->whereTime('create_time', 'between', $value);
    }

    /**
     * 新增前
     */
    public static function onBeforeInsert($model)
    {
        // 获取雪花ID配置
        $config = config('plugin.sqmadmin.snowflake');
        
        // 检查是否启用雪花ID
        if (!$config['enabled']) {
            return;
        }
        
        // 检查是否在例外表中
        $table = $model->getTable();
        if (in_array($table, $config['except_tables'] ?? [])) {
            return;
        }
        
        // 自动生成雪花ID
        if (!isset($model->id) || empty($model->id)) {
            $model->id = Snowflake::id();
            
            // 调试模式下记录日志
            if ($config['debug'] ?? false) {
                $log = "[Snowflake] Generated ID: {$model->id} for table: {$table}";
                file_put_contents(runtime_path() . '/logs/snowflake.log', $log . PHP_EOL, FILE_APPEND);
            }
        }
        
        $info = getCurrentInfo();
        $info && $model->setAttr('created_by', $info['id']);
    }

    /**
     * 写入前
     */
    public static function onBeforeWrite($model)
    {
        $info = getCurrentInfo();
        $info && $model->setAttr('updated_by', $info['id']);
    }

}